
package com.eltonkent.ui;

import java.util.ArrayList;

import android.app.Dialog;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import com.eltonkent.R;
import com.eltonkent.db.CustomTemplateTable;
import com.eltonkent.templates.SafeTemplateFactory;
import com.eltonkent.ui.adapters.SimpleIconListAdapter;
import com.eltonkent.ui.containers.SimpleIconListContainer;
import com.eltonkent.ui.containers.TemplateFieldContainer;
import com.eltonkent.util.ImageUtil;

public class CreateCustomTemplateActivity extends ParentActivity
{

	private LinearLayout contentView;
	private ArrayList<TemplateFieldContainer> entryFieldList;
	private EditText templateName;

	private View.OnClickListener imageClickListener = new View.OnClickListener()
	{

		@Override
		public void onClick(View v)
		{
			Log.d("UI", "Template icon clicked");
			/* Select icon dialog */
			showDialog(ApplicationConstants.DIALOG_SELECT);

		}
	};

	private Dialog getIconTemplateDialog()
	{
		final Dialog dialog = getCustomDialog(R.layout.dialog_listdisplay, R.string.template_select_icon);
		final ListView list = (ListView) dialog.findViewById(R.id.detailList);
		list.setOnItemClickListener(new AdapterView.OnItemClickListener()
		{
			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
			{
				SimpleIconListContainer container = (SimpleIconListContainer) list.getAdapter().getItem(
						arg2);
				getIntent().putExtra(ApplicationConstants.EXTRA_CUSTOM_ICON, container.getIconResource());
				setTemplateIcon();
				dialog.dismiss();
			}

		});
		return dialog;

	}

	@Override
	protected void onPrepareDialog(int id, final Dialog dialog)
	{
		switch(id)
		{
			case ApplicationConstants.DIALOG_SELECT:
				ListView list = (ListView) dialog.findViewById(R.id.detailList);
				SimpleIconListAdapter adapter = new SimpleIconListAdapter(getApplicationPreferences(),
						getApplicationContext(), R.layout.listview_icon_singleline, SafeTemplateFactory
								.getTemplateList(getApplicationContext(), R.xml.icons));
				list.setAdapter(adapter);
		}
	}

	private void addTemplateField(TemplateFieldContainer container, LayoutInflater inflater)
	{
		View view = inflater.inflate(R.layout.panel_templatefield, null);
		TextView title = (TextView) view.findViewById(R.id.templateTitle);
		TextView type = (TextView) view.findViewById(R.id.templateField);
		title.setText(container.getFieldName());
		type.setText(getFieldDescription(container.getFieldType()));
		view.setTag(container);
		contentView.addView(view);
	}

	private boolean doesFieldNameExist(String fieldName)
	{
		TemplateFieldContainer container;
		for(int i = 0; i < entryFieldList.size(); i++)
		{
			container = entryFieldList.get(i);
			if(container.getFieldName().equals(fieldName))
				return true;
		}
		return false;
	}

	private Dialog getAddFieldDialog()
	{
		final Dialog dialog = getCustomDialog(R.layout.dialog_addfield, R.string.addfield);
		final EditText fieldName = (EditText) dialog.findViewById(R.id.folderDesc);
		Button[] okCancel = getOKCancelButtons(dialog);
		Button btnok = okCancel[0];
		Button btnCancel = okCancel[1];
		final TextView errorText = (TextView) dialog.findViewById(R.id.errorText);
		final Spinner spinner = (Spinner) dialog.findViewById(R.id.spinner);
		ArrayAdapter<?> adapter = ArrayAdapter.createFromResource(this, R.array.field_types,
				android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		btnCancel.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View view)
			{
				errorText.setVisibility(View.GONE);
				fieldName.setText("");
				dialog.dismiss();
			}
		});
		btnok.setOnClickListener(new View.OnClickListener()
		{

			@Override
			public void onClick(View view)
			{
				if(fieldName.getText().toString().equals(""))
				{
					errorText.setText(R.string.template_fieldname_error);
					errorText.setVisibility(View.VISIBLE);
				} else if(doesFieldNameExist(fieldName.getText().toString()))
				{
					errorText.setText(R.string.template_fieldname_exits_error);
					errorText.setVisibility(View.VISIBLE);
				} else
				{
					errorText.setVisibility(View.GONE);
					int fieldType = 0;
					switch(spinner.getSelectedItemPosition())
					{
						case 0:/* text */
							fieldType = 1;
							break;
						case 1:/* number */
							fieldType = 2;
							break;
						case 2:/* date */
							fieldType = 4;
							break;
						case 3:/* email */
							fieldType = 32;
							break;

					}
					TemplateFieldContainer fieldContainer = new TemplateFieldContainer(fieldType, fieldName
							.getText().toString(), null);
					entryFieldList.add(fieldContainer);
					LayoutInflater inflater = LayoutInflater.from(getApplicationContext());
					addTemplateField(fieldContainer, inflater);
					dialog.dismiss();
				}
			}
		});
		return dialog;
	}

	private String getFieldDescription(int index)
	{
		// 1-text
		// 2-number
		// 4-date time
		// 131073-text multiline
		// 32-email address

		switch(index)
		{
			case 1:
				return getResources().getString(R.string.text);

			case 2:
				return getResources().getString(R.string.number);
			case 4:
				return getResources().getString(R.string.date);
			case 32:
				return getResources().getString(R.string.email);
			default:
				return getResources().getString(R.string.text);

		}
	}

	@Override
	protected final Dialog onCreateDialog(int id)
	{
		switch(id)
		{
			case ApplicationConstants.DIALOG_ADD:
				return getAddFieldDialog();
			case ApplicationConstants.DIALOG_SELECT:
				return getIconTemplateDialog();
			default:
				return super.onCreateDialog(id);
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu)
	{
		inflateMenu(menu, R.menu.createcustomtemplatemenu);
		return true;
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if(keyCode == KeyEvent.KEYCODE_BACK)
		{
			closeActivity(RESULT_CANCELED, getResources().getString(R.string.create));
			return true;
		}
		return false;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item)
	{
		switch(item.getItemId())
		{
			case R.id.mnu_AddEntry:
				showDialog(ApplicationConstants.DIALOG_ADD);
				return true;
			case R.id.mnu_Save:
				saveTemplate();
				return true;
		}

		return false;
	}

	@Override
	public ArrayList<TemplateFieldContainer> onRetainNonConfigurationInstance()
	{
		return entryFieldList;
	}

	@SuppressWarnings("unchecked")
	@Override
	protected void populateUI()
	{
		addToPath(getResources().getString(R.string.create));
		/* set template image from intent data */
		ImageView templateIcon = (ImageView) findViewById(R.id.templateIcon);
		templateIcon.setOnClickListener(imageClickListener);
		setTemplateIcon();
		templateName = (EditText) findViewById(R.id.templateName);
		/**/
		contentView = (LinearLayout) findViewById(R.id.contentLayout);
		entryFieldList = (ArrayList<TemplateFieldContainer>) this.getLastNonConfigurationInstance();
		if(entryFieldList == null)
		{
			entryFieldList = new ArrayList<TemplateFieldContainer>();
		}
		reloadContents();
	}

	private void setTemplateIcon()
	{
		ImageView templateIcon = (ImageView) findViewById(R.id.templateIcon);
		String iconPath = getIntent().getStringExtra(ApplicationConstants.EXTRA_CUSTOM_ICON);
		Bitmap image = ImageUtil.createBitmapFromAsset(getApplicationContext(), iconPath);
		templateIcon.setImageBitmap(image);
	}

	private void reloadContents()
	{
		// if (entryFieldList != null) {
		LayoutInflater inflater = LayoutInflater.from(getApplicationContext());

		for(int i = 0; i < entryFieldList.size(); i++)
		{
			addTemplateField(entryFieldList.get(i), inflater);
		}
		// }
	}

	private void showError(int error)
	{
		TextView errorText = (TextView) findViewById(R.id.errorText);
		errorText.setText(error);
		errorText.setVisibility(View.VISIBLE);
	}

	private boolean templateExists(String templateName)
	{
		CustomTemplateTable table = new CustomTemplateTable(getApplicationContext());
		return table.hasEntry(templateName);
	}

	private void saveTemplate()
	{
		if(templateName.getText().toString().equals(""))
		{
			showError(R.string.noname_custom_template);
		} else if(entryFieldList.size() == 0)
		{
			showError(R.string.nofields_custom_template);
		} else if(templateExists(templateName.getText().toString()))
		{
			showError(R.string.duplicate_custom_template);
		} else
		{
			CustomTemplateTable table = new CustomTemplateTable(getApplicationContext());
			table.addEntry(templateName.getText().toString(), entryFieldList, getIntent().getStringExtra(
					ApplicationConstants.EXTRA_CUSTOM_ICON));
			setResult(RESULT_OK);
			finish();
		}
	}

	@Override
	protected void setupUI(Bundle savedInstance)
	{
		setContentView(R.layout.activity_createcustomtemplate);

	}
}
